using AutoMapper;
using B.S.XZYData.Api.Wrter.Application.Command.Role;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Role
{
    public class UpdateRoleStateHandler : IRequestHandler<UpdateRoleStateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepo;
        private readonly IBaseRepository<PermissionRoleModel> _rolePermissionRepo;
        private readonly IBaseRepository<PermissionModel> _permissionRepo;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateRoleStateHandler> _logger;

        public UpdateRoleStateHandler(
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<PermissionRoleModel> rolePermissionRepo,
            IBaseRepository<PermissionModel> permissionRepo,
            IMapper mapper,
            ILogger<UpdateRoleStateHandler> logger)
        {
            _roleRepo = roleRepo;
            _rolePermissionRepo = rolePermissionRepo;
            _permissionRepo = permissionRepo;
            _mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 修改角色状态
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(UpdateRoleStateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var role = await _roleRepo.GetValue(request.RoleId);
                if (role == null || role.IsDeleted)
                {
                    return new ApiResult<int> { Msg = "角色不存在", Code = ApiEnum.Error };
                }
                role.IsState = request.State;
                int r = await _roleRepo.UpdateAsync(role);
                _logger.LogInformation($"修改角色状态{role.RoleName}成功!");
                return new ApiResult<int> { Msg = "修改角色状态成功!", Code = ApiEnum.Success, Data = r };
            }
            catch (Exception ex)
            {
                _logger.LogError("修改角色状态发生异常：" + ex.Message);
                return new ApiResult<int> { Msg = "修改角色状态发生异常：" + ex.Message, Code = ApiEnum.Error};
            }
        }
    }
} 